#coding=utf-8
from flask import Flask,render_template,session,redirect,url_for,flash
from app.main.forms import NameForm,EditProfileForm
from app.plan.forms import PlanForm
from app.models import User,Plan
from app.main import main
from flask_login import login_user,logout_user, login_required,current_user
from app import db
from app.auth.views import login


# @main.before_app_request
# def before_request():
# 	if current_user.is_authenticated:
# 		current_user.ping()
# 	else:
# 		return login()



'''首页'''
@main.route('/',methods=['GET','POST'])
def index():
	form=PlanForm()
	if form.validate_on_submit():
		post = Plan(
			plan_name=form.plan_name.data,
			plan_info=form.plan_info.data,
			subject_id=int(form.subject_id.data),
			status=1,
			creat_user=current_user._get_current_object()
		)
		db.session.add(post)
		db.session.commit()
		return redirect(url_for('.index'))
	plan_lists = Plan.query.filter_by(status=1).order_by(Plan.timestamp.desc()).all()
	return render_template('index.html', form=form, plan_lists=plan_lists)

@main.route('/delete/<plan_id>',methods=['GET','POST'])
def delet_plan(plan_id):
	db.session.query(Plan).filter(Plan.id ==plan_id).update({"status":2})
	db.session.commit()
	return redirect(url_for('.index'))


'''个人中心'''
@main.route('/user/<username>')
def user(username):
	user = User.query.filter_by(username=username).first_or_404()
	return render_template('user.html', user=user)


'''修改个人信息'''
@main.route('/edit-profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
	form = EditProfileForm()
	if form.validate_on_submit():
		current_user.username = form.name.data
		current_user.location= form.location.data
		current_user.about_me = form.about_me.data
		db.session.add(current_user._get_current_object())
		db.session.commit()
		flash('用户信息修改成功.')
		return redirect(url_for('.user', username=current_user.username))
	form.name.data = current_user.username
	form.location.data = current_user.location
	form.about_me.data = current_user.about_me
	return render_template('edit_profile.html', form=form)

